from rest_framework import serializers
from book.models import BookInfo,PeopleInfo

class PeopleInfoModelSerializers(serializers.ModelSerializer):
    """人物信息表"""

    # 关联表字段
    book_id = serializers.IntegerField(required=False)
    book = serializers.StringRelatedField()

    class Meta:
        model = PeopleInfo
        fields = ['id','book','book_id','name','password','is_delete']
        extra_kwargs = {
            'password':{'write_only':True},
            'is_delete':{'read_only':True}
        }

class BookInfoModelSerializers(serializers.ModelSerializer):
    """书籍信息表"""
    people = PeopleInfoModelSerializers(many=True)

    class Meta:
        model=BookInfo

        fields = '__all__'

    def create(self, validated_data):

        people = validated_data.pop('people')
        book = BookInfo.objects.create(**validated_data)

        for person in people:
            PeopleInfo.objects.create(book=book,**person)


        return book


